﻿using System;
using System.Linq;
using System.Web.Mvc;
using YourStore.Models;

namespace YourStore.Controllers
{
    [Authorize]
    public class CheckoutController : Controller
    {
        YourStoreEntities storeDB = new YourStoreEntities();
      

        //
        // GET: /Checkout/AddressAndPayment

        public ActionResult AddressAndPayment()
        {
            return View();
        }

        //
        // POST: /Checkout/AddressAndPayment

        [HttpPost]
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();
            TryUpdateModel(order);

            try
            {
                
                    order.Username = User.Identity.Name;
                    order.OrderDate = DateTime.Now;
                    storeDB.AddToOrders(order);
                    storeDB.SaveChanges();
                    
                    //Process the order
                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    var total = cart.GetTotal();
                    cart.CreateOrder(order);

                    var myorder = storeDB.Orders.Where(o => o.OrderId == order.OrderId).SingleOrDefault();
                    myorder.Total = total;
                    storeDB.SaveChanges();

                    Session["Total"] = total;
                    Session["OrderId"] = order.OrderId;
                    return RedirectToAction("PayPal");
                   // return RedirectToAction("Complete",
                        //new { id = order.OrderId });
                }
            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }

        //
        // GET: /Checkout/Complete
        public ActionResult PayPal()
        {
            return View();
        }
        
        public ActionResult Complete()
        {
            int id = Convert.ToInt32(Session["OrderId"]);
            // Validate customer owns this order
            bool isValid = storeDB.Orders.Any(
                o => o.OrderId == id &&
                o.Username == User.Identity.Name);

            if (isValid)
            {
                return View(id);
            }
            else
            {
                return View("Error");
            }
        }
    }
}